package com.elephant.createBan.resolveBeforeInstantiation;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;

/**
 * @author 林
 * @create 2025-06-12 15:38
 */
//MyInstantiationAwareBeanPostProcessors这个类会在bpp（registerBeanPostProcessors）的时候创建，然后到了
//finishBeanFactoryInitialization这个方法的时候会进行调用resolveBeforeInstantiation()方法进行处理
public class MyInstantiationAwareBeanPostProcessors implements InstantiationAwareBeanPostProcessor {
	//实例化之前
	@Override
	public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
		System.out.println("InstantiationAwareBeanPostProcessor:" + beanName + "--------执行postProcessBeforeInstantiation方法");
		//创建cglib代理对象
		if(beanClass.equals(BeforeInstantiation.class)){

			Enhancer enhancer=new Enhancer();
			enhancer.setSuperclass(beanClass);
			enhancer.setCallback(new MyMethodInterceptor());//执行回调接口
			BeforeInstantiation beforeInstantiation = (BeforeInstantiation) enhancer.create();
			System.out.println("创建代理对象"+beforeInstantiation);
			return beforeInstantiation;
		}
		return InstantiationAwareBeanPostProcessor.super.postProcessBeforeInstantiation(beanClass, beanName);
	}


	//实例化之后
	@Override
	public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {

		System.out.println("InstantiationAwareBeanPostProcessor:" + beanName + "--------执行postProcessBeforeInstantiation方法");

		return InstantiationAwareBeanPostProcessor.super.postProcessAfterInstantiation(bean, beanName);
	}

	@Override
	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
		System.out.println("InstantiationAwareBeanPostProcessor:" + beanName + "--------执行postProcessProperties方法");

		return InstantiationAwareBeanPostProcessor.super.postProcessProperties(pvs, bean, beanName);
	}

	//初始化之前，也可以在吃出进行实例化
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		System.out.println("BeanPostProcessor:" + beanName + "--------执行postProcessBeforeInitialization方法");
		return InstantiationAwareBeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
	}

	//初始化之后
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		System.out.println("BeanPostProcessor:" + beanName + "--------执行postProcessAfterInitialization方法");
		return bean;
	}
}
